package cn.mesmile.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/8/15 19:43
 * @Description
 */
public class ShareDemoLock {

    /**
     * 先答应 A->c1  再打印 B->c2   最后打印 C->c3
     * @param args
     */
    public static void main(String[] args) {
        ShareSource shareSource = new ShareSource();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareSource.printC1(i);
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareSource.printC2(i);
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareSource.printC3(i);
            }
        },"C").start();

    }

}


class ShareSource {

    private int flag = 1;

    ReentrantLock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void printC1(int loop){
        lock.lock();
        try {
            while (flag != 1){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+">>>>c1>>>轮数："+loop);
            flag = 2;
            // 通知c2
            c2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC2(int loop){
        lock.lock();
        try {
            while (flag != 2){
                c2.await();
            }
            System.out.println(Thread.currentThread().getName()+">>>>c2>>>轮数："+loop);
            flag = 3;
            // 通知c3
            c3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC3(int loop){
        lock.lock();
        try {
            while (flag != 3){
                c3.await();
            }
            System.out.println(Thread.currentThread().getName()+">>>>c3>>>轮数："+loop);
            flag = 1;
            // 通知 c1
            c1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
